from typing import List


class Solution:
    def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
        nums.sort()
        ret = []

        arr_len = len(nums)
        for i_idx in range(0, arr_len - 3):
            if i_idx > 0 and nums[i_idx] == nums[i_idx - 1]:
                continue
            for j_idx in range(i_idx + 1, arr_len - 2):
                if j_idx > i_idx + 1 and nums[j_idx] == nums[j_idx - 1]:
                    continue
                left = j_idx + 1
                right = arr_len - 1
                while left < right:
                    four_sum = nums[i_idx] + nums[j_idx] + nums[left] + nums[right]
                    if four_sum < target:
                        left += 1
                    elif four_sum == target:
                        ret.append([nums[i_idx], nums[j_idx], nums[left], nums[right]])
                        while left < right and nums[left] == nums[left + 1]:
                            left += 1
                        left += 1
                        while left < right and nums[right] == nums[right - 1]:
                            right -= 1
                        right -= 1
                    elif four_sum > target:
                        right -= 1
        return ret